#include "socket_client.h"

uint32_t main(void) {

	struct sockaddr_in my_addr;

	char buffer[MAX_BUFFER];
	uint32_t bytecount;
	uint32_t buffer_len = 0;

	uint32_t hsock;
	uint32_t *p_int;

	hsock = socket(AF_INET, SOCK_STREAM, 0);
	if (hsock == -1) {
		printf("Error en el socket()\n");
	}

	p_int = (uint32_t*) malloc(sizeof(uint32_t));
	*p_int = 1;

	if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*) p_int, sizeof(uint32_t)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*) p_int, sizeof(uint32_t)) == -1)) {
		printf("Error en el setsockopt()\n");
	}
	free(p_int);

	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(SERVER_PUERTO);

	memset(&(my_addr.sin_zero), 0, 8);
	my_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

	if (connect(hsock, (struct sockaddr*) &my_addr, sizeof(my_addr)) == -1) {
		printf("Error en el connect()\n");
	}

	buffer_len = MAX_BUFFER;

	memset(buffer, '\0', buffer_len);

	printf("Escribe un mensaje para enviar al servidor: \n");
	fgets(buffer, 1024, stdin);
	buffer[strlen(buffer)-1]='\0';

	if( (bytecount = send(hsock, buffer, strlen(buffer),0)) == -1){
		printf("Error en el send()\n");
	}

	printf("Enviados %d bytes \n", bytecount);

	if ((bytecount = recv(hsock, buffer, buffer_len, 0)) == -1){
		printf("Error en el recv()\n");
	}

	printf("Recibidos %d bytes\nMensaje recibido: \"%s\"\n", bytecount, buffer);

	close(hsock);

	return 0;
}
